<?php
declare (strict_types=1);

namespace app\common\model;
use think\model\relation\BelongsTo;
/**
 * 视频点赞
 * Class Video
 * @package app\common\model
 */
class UserVideoHit extends Base
{
    protected $name = 'user_video_hit';

    public function video(): BelongsTo
    {
        return $this->belongsTo(BusinessVideo::class, 'video_id', 'id')->field('id,introduce,cover,link');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uid', 'id')->field('id,nickname,photo,mobile');
    }

    public function getVideoLinkUrlAttr($value, $data): string
    {
        $link = BusinessVideo::where('id', $data['video_id'])->value('link');
        return $link ? $config = config('qiniu')['domain'].$link : '';
    }

    public static function hit($video_id, $uid): array
    {
        parent::startTrans();
        try {
            if($find = self::where(['video_id'=>$video_id, 'uid'=>$uid])->find()){
                $find->delete();
                BusinessVideo::where('id',$video_id)->dec('total_hit')->update();
                $msg = '取消成功';
            }else{
                $video = BusinessVideo::where('id',$video_id)->find();
                self::create([
                    'video_id' => $video_id,
                    'uid' => $uid,
                    'business_id' => $video->business_id
                ]);
                $video->total_hit ++ ;
                $video->save();
                $msg = '点赞成功';
            }
            parent::commit();
            return ['code' => 1, 'msg' => $msg];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
